package bible.sunflower.util.thread;

import java.util.HashMap;
import java.util.Map;

/**
 * 将线程局部变量作为中间存储器
 * @author zhangyp
 *
 */

public class ThreadLocalUtil {
	
	  private static ThreadLocal threadLocal = new ThreadLocal();

	  public static void setThreadAttribute(String key, Object obj){
	    Map threadLocalMap = (Map)threadLocal.get();
	    if (threadLocalMap == null) {
	      threadLocalMap = new HashMap();
	    }
	    threadLocalMap.put(key, obj);
	    threadLocal.set(threadLocalMap);
	  }

	  public static Object getThreadAttribute(String key){
	    Map threadLocalMap = (Map)threadLocal.get();
	    if (threadLocalMap == null) {
	      return null;
	    }
	    return threadLocalMap.get(key);
	  }

	  public static void removeThreadAttribute(String key){
	    Map threadLocalMap = (Map)threadLocal.get();
	    if (threadLocalMap != null) {
	      threadLocalMap.remove(key);
	      threadLocal.set(threadLocalMap);
	    }
	  }

	  public static void clearThreadAttributes(){
	    threadLocal.remove();
	  }
}
